package com.zhang.log4j2desensitization.config;


import com.zhang.log4j2desensitization.enums.DesensitizationTypeEnum;
import com.zhang.log4j2desensitization.utils.DesensitizationUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.layout.AbstractStringLayout;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * log4j2 脱敏插件
 * 继承AbstractStringLayout
 **/
@Plugin(name = "CustomPatternLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
public class CustomPatternLayout extends AbstractStringLayout {

    /**
     * LoggingEvent的属性 - message
     * 格式化前的日志信息，如log.info("your name : {}", "柳成荫")
     * message就是"your name : {}"
     */
    private static final String MESSAGE = "message";
    /**
     * LoggingEvent的属性 - formattedMessage
     * 格式化后的日志信息，如log.info("your name : {}", "柳成荫")
     * formattedMessage就是"your name : 柳成荫"
     */
    private static final String FORMATTED_MESSAGE = "formattedMessage";


    public final static Logger logger = LoggerFactory.getLogger(CustomPatternLayout.class);
    private final PatternLayout patternLayout;


    protected CustomPatternLayout(Charset charset, String pattern) {
        super(charset);
        patternLayout = PatternLayout.newBuilder().withPattern(pattern).build();
//        initRule();
    }

    /**
     * 要匹配的正则表达式map
     */
    private static final Map<String, Pattern> REG_PATTERN_MAP = new HashMap<>();
    private static final Map<String, String> KEY_REG_MAP = new HashMap<>();


    private void initRule() {
        try {
            if (MapUtils.isEmpty(Log4j2Rule.regularMap)) {
                return;
            }
            Log4j2Rule.regularMap.forEach((a, b) -> {
                if (StringUtils.isNotBlank(a)) {
                    Map<String, String> collect = Arrays.stream(a.split(",")).collect(Collectors.toMap(c -> c, w -> b, (key1, key2) -> key1));
                    KEY_REG_MAP.putAll(collect);
                }
                Pattern compile = Pattern.compile(b);
                REG_PATTERN_MAP.put(b, compile);
            });

        } catch (Exception e) {
            logger.info(">>>>>> 初始化日志脱敏规则失败 ERROR：{0}", e);
        }

    }

    /**
     * 处理日志信息，进行脱敏
     * 1.判断配置文件中是否已经配置需要脱敏字段
     * 2.判断内容是否有需要脱敏的敏感信息
     * 2.1 没有需要脱敏信息直接返回
     * 2.2 处理: 身份证 ,姓名,手机号,地址敏感信息
     */
    public String hideMarkLog(String logStr) {
        try {
            //1.判断配置文件中是否已经配置需要脱敏字段
            if (StringUtils.isBlank(logStr) || MapUtils.isEmpty(Log4j2Rule.KEY_REG_MAP) || MapUtils.isEmpty(Log4j2Rule.REG_PATTERN_MAP)) {
                return logStr;
            }
            //2.判断内容是否有需要脱敏的敏感信息
            Set<String> charKeys = Log4j2Rule.KEY_REG_MAP.keySet();
            for (String key : charKeys) {
                if (logStr.contains("<" + key + ">"))
                    logStr = this.handleXmlLogStr(logStr, key);
                else if (logStr.contains(key)) {
                    String regExp = Log4j2Rule.KEY_REG_MAP.get(key);
                    logStr = matchingAndEncrypt(logStr, regExp, key);
                }
            }
            return logStr;
        } catch (Exception e) {
            logger.info(">>>>>>>>> 脱敏处理异常 ERROR:{0}", e);
            //如果抛出异常为了不影响流程，直接返回原信息
            return logStr;
        }
    }

    /**
     *  处理xml格式的日志信息，进行逐对敏感操作
     * @param logStr  xml格式的日志信息
     * @param key 需要逐对敏感操作的字段名称
     * @return 逐对敏感操作后的日志信息
     * @throws Exception
     */
    private String handleXmlLogStr(String logStr, String key) throws Exception {
        int start = logStr.indexOf("<" + key + ">") + key.length() + 2;
        int end = logStr.indexOf("</" + key + ">");
        if (end < 0)
            return logStr;
        String originStr = logStr.substring(start, end);
        String hiddenStr = "";
        StringBuffer result = new StringBuffer(logStr);
        //处理脱敏信息 如 <phone>1123231114</phone> ==> <phone>112****1114</phone>
        hiddenStr = this.handleOriginStrByKey(originStr, key);
        logStr = result.replace(start, end, hiddenStr).toString();
        return logStr;
    }

    /**
     * 正则匹配对应的对象。
     *
     * @param msg    日志对象
     * @param regExp 正则匹配
     * @param key    字段
     * @return 找到对应对象
     */
    private static String matchingAndEncrypt(String msg, String regExp, String key) {
        Pattern pattern = Pattern.compile(regExp);
        Matcher matcher = pattern.matcher(msg);

        int length = key.length() + 3;
        String hiddenStr = "";
        StringBuffer result = new StringBuffer(msg);
        int i = 0;
        while (matcher.find()) {
            String originStr = matcher.group();
            // 计算关键词和需要脱敏词的距离小于5。
            i = msg.indexOf(originStr);
            if (i < 0) {
                continue;
            }
            int span = i - length;
            int startIndex = Math.max(span, 0);
            String substring;
            if (startIndex > 2) {
                substring = msg.substring(startIndex - 2, i);
            } else {
                substring = msg.substring(startIndex, i);
            }

            if (StringUtils.isBlank(substring) || !substring.contains(key)) {
                i += key.length();
                continue;
            }
            //按照关键字 处理对应脱敏信息
            hiddenStr = handleOriginStrByKey(originStr, key);
            msg = result.replace(i, i + originStr.length(), hiddenStr).toString();
        }
        return msg;
    }

    /**
     * 根据脱敏关键字 替换对应的字符并脱敏。
     * @param originStr  原始字符串
     * @param key        脱敏关键字
     * @return
     */
    private static String handleOriginStrByKey(String originStr, String key){
        String hiddenStr = "";
        boolean names = Log4j2Rule.USER_NAME_STR.contains(key);
        boolean address = Log4j2Rule.USER_ADDRESS_STR.contains(key);
        boolean phones = Log4j2Rule.USER_PHONE_STR.contains(key);
        boolean idCard = Log4j2Rule.USER_IDCARD_STR.contains(key);
        boolean email = Log4j2Rule.USER_MAIL_STR.contains(key);
        boolean bankCard = Log4j2Rule.USER_BANK_CARD_STR.contains(key);
        if (names) {
            hiddenStr = hideMarkStr(originStr, DesensitizationTypeEnum.NAMES.getType());
        } else if (phones) {
            hiddenStr = hideMarkStr(originStr, DesensitizationTypeEnum.PHONE.getType());
        } else if (address) {
            hiddenStr = hideMarkStr(originStr, DesensitizationTypeEnum.ADDRESS.getType());
        } else if (idCard) {
            hiddenStr = hideMarkStr(originStr, DesensitizationTypeEnum.IDCARD.getType());
        } else if (email) {
            hiddenStr = hideMarkStr(originStr, DesensitizationTypeEnum.EMAIL.getType());
        } else if (bankCard) {
            hiddenStr = hideMarkStr(originStr, DesensitizationTypeEnum.BANKCARD.getType());
        }
        return hiddenStr;
    }

    /**
     * 标记敏感文字规则
     *
     * @param needHideMark 日志对象
     * @param type         脱敏规则类型  1为姓名脱敏规则，2为姓名脱敏规则手机号，3为地址脱敏规则，
     * @return 返回过敏字段
     */
    private static String hideMarkStr(String needHideMark, int type) {
        if (StringUtils.isBlank(needHideMark) || "null".equals(needHideMark)) {
            return "";
        }
        int startSize = 0, endSize = 0, mark = 0, length = needHideMark.length();

        StringBuffer hideRegBuffer = new StringBuffer("(\\S{");
        StringBuffer replaceSb = new StringBuffer("$1");
        if (type == DesensitizationTypeEnum.NAMES.getType()) {
            startSize = 1;
        } else if (type == DesensitizationTypeEnum.PHONE.getType()) {
            int i = length / 3;
            startSize = i;
            endSize = i + 1;
        } else if (type == DesensitizationTypeEnum.ADDRESS.getType()) {
            startSize = 3;
        } else if (type == DesensitizationTypeEnum.IDCARD.getType()) {
            startSize = 6;
            endSize = 4;
        } else if (type == DesensitizationTypeEnum.EMAIL.getType()) {
            startSize = 3;
            endSize = length - needHideMark.indexOf("@");
        } else if (type == DesensitizationTypeEnum.BANKCARD.getType()) {
            startSize = 6;
            endSize = startSize + 1;
        }
        mark = length - startSize - endSize;
        for (int i = 0; i < mark; i++) {
            replaceSb.append("*");
        }
        hideRegBuffer.append(startSize).append("})\\S*(\\S{").append(endSize).append("})");
        replaceSb.append("$2");
        needHideMark = needHideMark.replaceAll(hideRegBuffer.toString(), replaceSb.toString());
        return needHideMark;
    }


    /**
     * 创建插件
     */
    @PluginFactory
    public static Layout createLayout(@PluginAttribute(value = "pattern") final String pattern,
                                      @PluginAttribute(value = "charset") final Charset charset) {
        return new CustomPatternLayout(charset, pattern);
    }


    @Override
    public String toSerializable(LogEvent event) {
        return hideMarkLog(patternLayout.toSerializable(event));
    }


}
